package com.wangtao.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String>{
    //定义channel集合
    //GlobalEventExecutor 全局事件管执行器
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  //  private static ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取到当前channel
        Channel channel = ctx.channel();
        channelGroup.forEach(ch->{
            if (channel != ch) {
                ch.writeAndFlush(sd.format(new Date())+"\t"+"[客户]" + channel.remoteAddress() + " 发送了消息:" + msg+"\n");
            }else{
                ch.writeAndFlush(sd.format(new Date())+"\t"+"[自己]发送了消息:" + msg + "\n");
            }
        });

    }

    //连接建立第一个执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //该客户端加入聊天信息推送给其他客户端
        channelGroup.writeAndFlush(sd.format(new Date())+"\t"+"[客户端]" + channel.remoteAddress() + "加入聊天\n");
        channelGroup.add(channel);

    }

    //通道就绪时
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sd.format(new Date())+"\t"+ctx.channel().remoteAddress() + "上线了...");
    }

    //当通道非活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sd.format(new Date())+"\t"+ctx.channel().remoteAddress() + "离线了...");
    }

    //断开连接触发
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(sd.format(new Date())+"\t"+"[客户端]" + channel.remoteAddress() + "离开了\n");
        System.out.println(sd.format(new Date())+"\t"+"当前channelGroup size:"+channelGroup.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
